package com.purchasing.system.config;

import com.purchasing.system.model.ERole;
import com.purchasing.system.model.Permission;
import com.purchasing.system.model.Role;
import com.purchasing.system.repository.PermissionRepository;
import com.purchasing.system.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Configuration
public class DataLoader {

    private final PermissionRepository permissionRepository;
    private final RoleRepository roleRepository;

    @Autowired
    public DataLoader(PermissionRepository permissionRepository,
                      RoleRepository roleRepository) {
        this.permissionRepository = permissionRepository;
        this.roleRepository = roleRepository;
    }

    @Bean
    public CommandLineRunner initData() {
        System.out.println("Initializing data...");
        return args -> {
            // 初始化基础权限
            initBasicPermissions();
            // 初始化角色并关联权限
            initRolesWithPermissions();
        };
    }

    private void initBasicPermissions() {
        // 系统基础权限
        ensurePermissionExists("dashboard:view", "查看仪表盘");
        ensurePermissionExists("user:management", "用户管理");
        ensurePermissionExists("notification:read", "查看通知");
        ensurePermissionExists("role:management", "角色管理");
        ensurePermissionExists("profile:manage", "管理个人信息");

        // 采购申请相关权限
        ensurePermissionExists("purchase_request:create", "创建采购申请");
        ensurePermissionExists("purchase_request:read", "查看采购申请");
        ensurePermissionExists("purchase_request:read_detail", "查看采购申请详情");
        ensurePermissionExists("purchase_request:update", "更新采购申请");
        ensurePermissionExists("purchase_request:delete", "删除采购申请");

        // 审批流程相关权限
        ensurePermissionExists("approval:review", "审批流程");
        ensurePermissionExists("approval_history:read", "查看审批历史");

        // 用户相关基础权限
        ensurePermissionExists("user:create", "创建用户");
        ensurePermissionExists("user:read", "查看用户");
        ensurePermissionExists("user:update", "修改用户");
        ensurePermissionExists("user:delete", "删除用户");
        System.out.println("Initialized basic permissions.");
    }

    @Transactional
    public void ensurePermissionExists(String name, String description) {
        if (!permissionRepository.existsByName(name)) {
            Permission permission = new Permission();
            permission.setName(name);
            permission.setDescription(description);
            permissionRepository.save(permission);
            System.out.println("Created permission: " + name);
        }else{
            System.out.println("Permission already exists: " + name);
        }
    }

    // 初始化角色并关联权限，这里权限是初始权限，后续可修改
    private void initRolesWithPermissions() {
        // 超级管理员角色（拥有所有权限）
        createRoleIfNotExists(ERole.ROLE_SUPER_ADMIN,
                Arrays.asList("dashboard:view","user:management","notification:read","role:management","profile:manage"));

        // 管理员角色（拥有用户管理权限）
        createRoleIfNotExists(ERole.ROLE_ADMIN,
                Arrays.asList("dashboard:view","purchase_request:read_detail","approval:review","approval_history:read",
                        "notification:read"));

        // 普通员工角色（基础权限）
        createRoleIfNotExists(ERole.ROLE_EMPLOYEE,
                Arrays.asList("dashboard:view","purchase_request:read","purchase_request:create","purchase_request:update",
                        "notification:read"));
        System.out.println("Initialized roles with permissions.");
    }

    private void createRoleIfNotExists(ERole roleName, List<String> permissionNames) {
        // 查找或创建角色
        Role role = roleRepository.findByName(roleName)
                .orElseGet(() -> {
                    Role newRole = new Role();
                    newRole.setName(roleName);
                    return roleRepository.save(newRole);
                });

        // 获取请求的权限列表
        Set<Permission> requiredPermissions = new HashSet<>(
                permissionRepository.findByNameIn(permissionNames)
        );

        // 检查当前权限是否需要更新
        if (!role.getPermissions().containsAll(requiredPermissions)) {
            // 合并现有权限和新权限（避免删除已存在的额外权限）
            Set<Permission> mergedPermissions = new HashSet<>(role.getPermissions());
            mergedPermissions.addAll(requiredPermissions);

            role.setPermissions(mergedPermissions);
            roleRepository.save(role);

            System.out.println("Updated role '" + roleName + "' with permissions: " +
                    String.join(", ", permissionNames));
        } else {
            System.out.println("Role '" + roleName + "' already has required permissions");
        }
    }
}